package cn.yj.core.event.listener;

import cn.yj.cgs.dba.entity.Message;
import cn.yj.common.AppExecutor;
import cn.yj.common.config.BeanTool;
import cn.yj.commons.utils.StringUtils;
import cn.yj.core.business.service.MessageService;
import cn.yj.core.event.EventSource;
import cn.yj.core.event.KeyWorkFilterEvent;
import cn.yj.email.EmailType;
import cn.yj.email.handle.DefaultEmailHandler;
import cn.yj.email.handle.Email;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

/**
 * 内容违规过滤事件监听器
 *
 * @author 永健
 * @since 2021-10-16 22:40
 */
@Component
public class KeyWordFilterEventListener implements ApplicationListener<KeyWorkFilterEvent> {

    private static final Logger LOGGER = LoggerFactory.getLogger(KeyWordFilterEventListener.class);

    @Resource
    private MessageService messageService;

    @Override
    public void onApplicationEvent(KeyWorkFilterEvent keyWorkFilterEvent) {
        EventSource source = (EventSource) keyWorkFilterEvent.getSource();
        Set<String> keyWord = source.getKeyWord();

        if (!keyWord.isEmpty()) {
            LOGGER.warn("内容违规检测,发布人={}", source.getUserCode());
            LOGGER.warn("内容违规检测内容={}", source.getContent());
            LOGGER.warn("内容违规检测到关键词={}", StringUtils.join(keyWord, ","));

            String errorMsg = "系统检测到你发布内容疑似存在敏感词 [ " + StringUtils.join(keyWord, ",") + "],文章需要审核方可通过!  请同学文明用语哦～";
            // 邮件通知
            messageService.notice(new Message(errorMsg, "违规提示", source.getUserCode()));

            Email email = new Email(EmailType.敏感词检测通知, "检测到用户发布的内容存在违规敏感词：<br/><br/>" + source.getContent() + " " +
                    " " + "<br/><br/>\n " + "疑似敏感词：\n<br/><br/>" + JSON.toJSONString(keyWord));
            email.setRecEmail(email.getFrom());
            AppExecutor.exec(() -> BeanTool.getBean(DefaultEmailHandler.class).sendEmail(email));

            // TODO 记录用户违规次数
        }
    }
}
